package com.sxt.netty.server.init;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import com.sxt.common.Const;
import com.sxt.netty.server.handler.ServerHandler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
//import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * 网络事件处理器 
 * 
 * @program: SpringBoot+Netty+Redis
 * @Date: 2020/09/23 09:20
 * @Author: luolin
 * @Description: 服务器Channel通道初始化设置
 */
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel>{

	@Override
	protected void initChannel(SocketChannel socketChannel) throws Exception {
		ChannelPipeline pipeline = socketChannel.pipeline();
		// 监测心跳,15分钟没有收到消息 将IdleStateHandler 添加到 ChannelPipeline 中
		pipeline.addLast("ping", new IdleStateHandler(Const.READER_IDLE_TIME_SECONDS, 0, 0, TimeUnit.MINUTES));
		pipeline.addLast(new LineBasedFrameDecoder(1024));
		//pipeline.addLast(new StringDecoder(Charset.forName("UTF-8")));//  消息转成String解码器
		pipeline.addLast(new StringEncoder(Charset.forName("UTF-8")));//  消息转成String编码器
		// 处理网络IO
		pipeline.addLast(new ServerHandler());
	}

}
